package wavequote;

import com.google.wave.api.*;

import java.util.ArrayList;
import java.util.Random;
import java.io.*;
import java.net.MalformedURLException;

public class WaveQuoteServlet extends AbstractRobotServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3506171628945118006L;
	
	private static ArrayList<String> theQuotes = new ArrayList<String>();

	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		
		if (bundle.wasSelfAdded()){
			Blip b = wavelet.appendBlip();
			TextView t = b.getDocument();
			t.append("\"I'm here, and you can quote me!\" Type three quotes like this \"\"\" to get a quote.");
			try {
				readInQuotes();
			} catch (FileNotFoundException e1) {	
			} catch (IOException e) {
			}
			
		}
		
        for (Event e : bundle.getEvents()) {
            if (e.getType() == EventType.BLIP_SUBMITTED) {
                    submit(wavelet, e.getBlip());
            }
        }

	}
	
	private void readInQuotes() throws IOException
	{
		try{
		BufferedReader reader = new BufferedReader(new FileReader("quotes.txt"));
        String line;
        while ((line = reader.readLine()) != null) {
            theQuotes.add(line);
        }
        reader.close();

		} catch (MalformedURLException e) {
        // ...
		} catch (IOException e) {
        // ...
		}
	}
	
	private void submit(Wavelet wavelet, Blip blip)
	{
		TextView t = blip.getDocument();
		String str = t.getText();
		if (str.indexOf("\"\"\"") != -1){
			addQuote(t);
		}
	}
	
	private void addQuote(TextView t)
	{
		Random r = new Random();
		//int index = r.nextInt(quotes.length - 1);
		//t.append("\n" + quotes[index] + " " + theQuotes.size());
		int index = r.nextInt(theQuotes.size()-1);
		t.append("\n" + theQuotes.get(index));
		
	}
}
